package com.wg.msorderds.serviceImp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wg.msorderds.Maaper.OrderDetailsMapper;
import com.wg.msorderds.Maaper.OrdertbMapper;
import com.wg.msorderds.entity.OrderDetails;
import com.wg.msorderds.entity.OrderProductInfo;
import com.wg.msorderds.entity.Ordertb;
import com.wg.msorderds.entity.UserAddress;
import com.wg.msorderds.service.IOrdertbService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OrdertbServiceImpl extends ServiceImpl<OrdertbMapper, Ordertb>
        implements IOrdertbService {

    @Autowired
    private OrderDetailsMapper orderDetailsMapper; // 注入 OrderDetailsMapper

    @Autowired
    private OrdertbMapper ordertbMapper;

    @Override
    public List<Ordertb> selectByUserId(Integer userId) {
        return this.baseMapper.selectByUserId(userId);
    }
    @Override
    public Ordertb getLatestOrderByUserId(Integer userId) {
        // 调用Mapper方法获取最新订单
        List<Ordertb> orders = this.baseMapper.selectByUserId(userId);
        // 返回第一条记录（因为SQL已按时间倒序排列）
        return orders.isEmpty() ? null : orders.get(0);
    }
    @Override
    @Transactional
    public int createOrder(Ordertb order, List<OrderDetails> orderDetails) {
        // 保存订单主表
        boolean orderSaved = this.save(order);
        if (!orderSaved) {
            throw new RuntimeException("订单保存失败");
        }

        // 设置订单详情的订单ID

        for (OrderDetails detail : orderDetails) {
            detail.setOrderId(order.getId());
            if (orderDetailsMapper.insert(detail) <= 0) {
                throw new RuntimeException("订单详情保存失败");
            }
        }
        // 返回订单ID
        return order.getId();
    }

    @Override
    public List<Ordertb> getTimeoutUnpaidOrders(int minutes) {
        // 查询指定分钟数前创建的未支付订单
        QueryWrapper<Ordertb> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0); // 0表示未支付

        // 计算超时时间点
        Date timeoutTime = new Date(System.currentTimeMillis() - minutes * 60 * 1000L);
        queryWrapper.lt("create_time", timeoutTime);

        return this.list(queryWrapper);
    }
    @Override
    @Transactional
    public boolean cancelOrder(Integer orderId) {
        Ordertb order = this.getById(orderId);
        if (order == null) {
            return false;
        }

        // 只有待支付的订单才能取消
        if (order.getStatus() != 0) {
            return false;
        }

        // 更新订单状态为已取消（状态4）
        order.setStatus(4);
        order.setUpdateTime(new Date());

        return this.updateById(order);
    }

    @Override
    @Transactional
    public boolean cancelOrderByUser(Integer orderId) {
        Ordertb order = this.getById(orderId);
        if (order == null) {
            return false;
        }

        // 只有待支付的订单才能取消
        if (order.getStatus() != 0) {
            return false;
        }

        // 更新订单状态为已取消（状态4）
        order.setStatus(4);
        order.setUpdateTime(new Date());

        return this.updateById(order);
    }
    public int updateStatusToPaid(Integer orderId){
        return this.baseMapper.updateStatusToPaid(orderId);
    }
    @Override
    public List<OrderProductInfo> getAllOrders(Integer userId) {
        return ordertbMapper.getOrderProductsByUserId(userId);
    }
}
